<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NSpace align="center">
          入库出库时间:
          <NDatePicker
            input-readonly
            style="width: 280rem"
            placeholder="请选择出入库时间"
            clearable
            type="daterange"
            @update-formatted-value="handleFormattedStart"
          />
          审批状态:
          <NSelect
            style="width: 150rem"
            placeholder="请选择审批状态"
            v-model:value="paginationReactive.fromStatusCode"
            clearable
            :options="statusList"
          />
          <NButton
            type="primary"
            style="width: 78rem"
            ghost
            @click="() => ((paginationReactive.page = 1), getInOutList())"
          >
            查询
          </NButton>
        </NSpace>
        <NButton
          type="primary"
          style="width: 115rem"
          @click="$router.push({ name: 'OA/PersonnelInStorage/InOutAdd' })"
        >
          入库申请
        </NButton>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable
        v-bind="props"
        :bordered="false"
        :columns="columns"
        :data="tableData"
        :pagination="false"
        :loading="tableLoading"
      />
    </template>

    <template #pagination>
      <NPagination
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker
        show-quick-jumper
        :suffix="() => '页'"
      >
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
    @close="modalVisible = false"
  >
    <VDialogContent
      @close="modalVisible = false"
      @submit="recall"
      title="撤回提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定撤回该入库申请吗？
      </div>
    </VDialogContent>
  </NModal>
</template>
<script setup lang="ts">
import {
  NSpace,
  NInput,
  NButton,
  NSelect,
  NDataTable,
  NPagination,
  NDatePicker,
  useMessage
} from 'naive-ui'
import { h, onDeactivated, reactive, ref, watch } from 'vue'
import { useViewerStore } from '../Common/store'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import type { DisModel } from '@/api/receiveOrDispatch'
import type { HttpResponse } from '@/utils/http'
import { type DataTableColumns, NModal } from 'naive-ui'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import router from '@/router'
import { RecordType } from '@/router/utils'

const message = useMessage()
const useStore = useViewerStore()
const route = useRoute()
const modalVisible = ref(false)
const statusList = [
  { label: '草稿', value: 'A0601' },
  { label: '撤销', value: 'A0602' },
  { label: '审批中', value: 'A0603' },
  { label: '拒绝', value: 'A0604' },
  { label: '通过', value: 'A0605' }
]
const columns: DataTableColumns = [
  {
    title: '申请人',
    key: 'userName',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '入库时间',
    key: 'inTime',
    width: 160,
    align: useStore.isCenter
  },
  {
    title: '出库时间',
    key: 'outTime',
    width: 160,
    align: useStore.isCenter
  },
  {
    title: '入库原因',
    key: 'reasons',
    width: 100,
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  /*{
    title: '出入区域',
    key: 'region',
    width: 100,
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400px'
        }
      }
    }
  },
  {
    title: '是否进入山体库',
    key: 'massifFlag',
    width: 80,
    align: useStore.isCenter,
    render: (e: any) => {
      return e.massifFlag === null ? null : e.massifFlag === 0 ? '否' : '是'
    }
  },*/
  {
    title: '提交时间',
    key: 'submitTime',
    width: 160,
    align: useStore.isCenter
  },
  {
    title: '审批状态',
    key: 'fromStatus',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
    width: 150,
    fixed: 'right',
    render: (row: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            RecordType.setRouteNameTypeFalse('A0581')
            router.push({ path: '/OA/PersonnelInStorage/InOutDetail', query: { id: row.id } })
          }
        },
        {
          default: () => '详情'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: { display: row.fromStatusCode != 'A0603' ? 'inlne-block' : 'none' },
          onClick: () => {
            router.push({
              path: '/OA/PersonnelInStorage/InOutUpdate',
              query: { id: row.id, flag: 1 }
            })
          }
        },
        {
          default: () => '再次发起'
        }
      ),
      h(
        NButton,
        {
          type: 'info',
          loading: row.exportLoading || false,
          quaternary: true,
          style: {
            display: row.fromStatusCode == 'A0605' ? 'inline-flex' : 'none'
          },
          onClick: () => handleExport(row)
        },
        {
          default: () => '导出'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: { display: row.fromStatusCode == 'A0603' ? 'inlne-block' : 'none' },
          onClick: async () => {
            recallId.value = row.id
            modalVisible.value = true
          }
        },
        {
          default: () => '撤回'
        }
      )
    ]
  }
]

const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  inTime: null, //开始请假的开始时间
  outTime: null, //开始请假的结束时间
  fromStatusCode: null, //审批状态
  onChange: (page: number) => {
    paginationReactive.page = page
    getInOutList()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    getInOutList()
  }
})
// 开始时间选择
const handleFormattedStart = (v: any) => {
  if (v) (paginationReactive.inTime = v[0]), (paginationReactive.outTime = v[1])
  else (paginationReactive.inTime = null), (paginationReactive.outTime = null)
}
// 获取列表
const tableData = ref()
const tableLoading = ref(false)
const getInOutList = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'inStorage',
    api: 'inoutList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        inTime: paginationReactive.inTime ? paginationReactive.inTime + ' 00:00:00' : null,
        outTime: paginationReactive.outTime ? paginationReactive.outTime + ' 23:59:59' : null,
        fromStatusCode: paginationReactive.fromStatusCode
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = []
  setTimeout(() => {
    tableData.value = res.data.list.map((r: any) => {
      return {
        ...r,
        exportLoading: false
      }
    })
    paginationReactive.itemCount = res.data.totalCount
  }, 0)
}
//导出
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
const exportLoading = ref(false)
async function handleExport(val: any) {
  tableData.value.forEach((t: any) => {
    t.exportLoading = String(t.id) === String(val.id)
  })
  const [error, data, headers] = await sendRequest({
    module: 'inStorage',
    api: 'inoutExport',
    override: {
      params: {
        peoplePassId: val.id
      }
    }
  })
  if (error) {
    tableData.value.forEach((t: any) => {
      t.exportLoading = false
    })
    return message.error(error.message)
  }
  tableData.value.forEach((t: any) => {
    t.exportLoading = false
  })
  download(headers, data, '杭州国家版本馆外来人员临时入库申请表')
}
// 撤回
const recallId = ref()
const recall = async () => {
  modalVisible.value = false
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<DisModel>>({
    module: 'inStorage',
    api: 'inoutrevoke',
    override: {
      params: {
        id: recallId.value
      }
    }
  })
  if (error) return message.error('撤回失败')
  if (res.code !== 0) return message.error('撤回失败')
  getInOutList()
  message.success('撤回成功')
}

const keyUpDown = (e: any) => e.key == 'Enter' && ((paginationReactive.page = 1), getInOutList())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route,
  async () => {
    if (route.path == '/OA/PersonnelInStorage/index') {
      getInOutList()
      window.addEventListener('keyup', keyUpDown, false) // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>
<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}
</style>
